import requests
from plugins import Plugin
from bridge.context import EventContext, ContextType, EventAction
from bridge.reply import Reply, ReplyType
from common.log import logger

# 定义API的基础URL
BASE_URL_BCGM = "https://api.qqsuu.cn/api/dm-bcgm"

# 注册插件
@Plugin.register(name="bcgm",
                  desc="本草纲目查询",
                  version="1.0",
                  author="wyh",
                  desire_priority=100)
class BcgmPlugin(Plugin):

    def __init__(self):
        super().__init__()
        self.handlers[EventContext.ON_HANDLE_CONTEXT] = self.on_handle_context
        logger.info(f"[{__class__.__name__}] inited")

    def get_help_text(self, **kwargs):
        help_text = "发送【本草纲目 对应药品名称】查询药品详细信息"
        return help_text

    def on_handle_context(self, e_context: EventContext):
        # 只处理文本消息
        if e_context['context'].type != ContextType.TEXT:
            return
        content = e_context["context"].content.strip()
        # 检查是否以"本草纲目"开头
        if content.startswith("本草纲目"):
            logger.info(f"[{__class__.__name__}] 收到查询请求: {content}")
            reply = Reply()
            result = self.query_bcgm(content)
            if result:
                reply.type = ReplyType.TEXT
                reply.content = result
                e_context["reply"] = reply
                e_context.action = EventAction.BREAK_PASS
            else:
                reply.type = ReplyType.ERROR
                reply.content = "获取失败，请稍后重试"
                e_context["reply"] = reply
                e_context.action = EventAction.BREAK_PASS

    def query_bcgm(self, query):
        try:
            # 提取药品名称
            drug_name = query.replace("本草纲目 ", "")
            params = {"name": drug_name}
            headers = {'Content-Type': "application/x-www-form-urlencoded"}
            response = requests.get(url=BASE_URL_BCGM, params=params, headers=headers, timeout=10)
            response.raise_for_status()

            json_data = response.json()
            logger.info(f"API响应: {json_data}")

            if json_data.get('code') == 200 and json_data['result']['list']:
                data = json_data['result']['list'][0]
                return f"本草纲目查询结果：\n药品名称：{data['name']}\n详细内容：{data['content']}"
            else:
                logger.error(f"API返回值异常: {json_data.get('msg')}")

        except requests.exceptions.HTTPError as http_err:
            logger.error(f"HTTP错误: {http_err}")
        except requests.exceptions.ConnectionError as conn_err:
            logger.error(f"连接错误: {conn_err}")
        except requests.exceptions.Timeout as timeout_err:
            logger.error(f"请求超时: {timeout_err}")
        except requests.exceptions.RequestException as req_err:
            logger.error(f"请求异常: {req_err}")
        except Exception as e:
            logger.error(f"其他错误: {e}")

        return None

